package com.shu.Algorithm;

import lombok.Data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Optional;

/**
 * @author ssm
 * @version V1.0
 * @description:
 * @date 2021/8/26 16:03
 */

public class ExceptionTest {

    /**
     * @param args
     * @return
     * @throws RuntimeException 测试中会抛出运行时异常
     * @throws IOException      受检异常抛出去吧
     */
    public static void main(String[] args) throws IOException {

        /**
         * AutoCloseable
         * try-with-resource 使用这种写法可以在资源使用完毕自动释放,因为他实现了AutoCloseable接口
         */
        try (FileInputStream fs2 = new FileInputStream(new File("C:\\1.txt"));) {
            System.out.println("1111");
        } catch (IOException e) {
            System.out.println("1111");
        }

        FileInputStream fs1 = null;
        try {
            fs1 = new FileInputStream(new File("C:\\1.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fs1 != null) {
                try {
                    fs1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        test(null);


        // Optional 来防止NPE
        User user = new User();
        Optional<User> userOptional = Optional.ofNullable(user);

        User user1 = Optional.ofNullable(user).orElse(new User());

        userOptional.ifPresent((x) -> {
            System.out.println(x.toString());
        });

        try {
            System.out.println("try");
            throw new RuntimeException("123123");
        } catch (Exception e) {
            System.out.println("catch");
            return;
        } finally {
            System.out.println("finally");
            return;
        }


    }

    /**
     * 拆箱NPE
     *
     * @param x
     * @return
     */
    private static int test(Integer x) {
        return x;
    }

    @Data
    static class User {
        private String name;
        private Integer age;
    }
}
